package com.infFem2011.db.client;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.h2.jdbcx.JdbcConnectionPool;

import com.informaticaFeminale2011.interfaces.Settings;

public class DBAccessor {
	private static String PORT = "8082";
	private static String DRIVER = "org.h2.Driver", URL_1 = "jdbc:h2:~/test",
			URL_ = "jdbc:h2:tcp://10.121.37.46:" + PORT + "/~/test",
			URL_LOCALHOST = "jdbc:h2:tcp://localhost/~/test", DB = "test",
			URL = "jdbc:h2:localhost:8082/~/test",
			IP_PORT = "http://10.121.37.46:8082";
	// tjdbc:h2:tcp://localhost/~/test
	private Connection conn = null;

	public void connect() throws SQLException, ClassNotFoundException {
		Class.forName(DRIVER);
		if (true)
			conn = DriverManager.getConnection(URL, "inffem2011", "2011");
		else
			conn = DriverManager.getConnection(URL, "sa", "");
	}

	public void close() throws SQLException {
		if (conn != null) {
			conn.close();
			conn = null;
		}
	}

	public void userConnectionPools() throws Exception {
		String[] args = { "select ID, NAME from TEST ",
				"select ID, NAME from TEST " };
		JdbcConnectionPool cp = JdbcConnectionPool.create(URL, "sa", "");
		for (int i = 0; i < args.length; i++) {
			Connection conn = cp.getConnection();
			conn.createStatement().execute(args[i]);
			conn.close();
		}
		cp.dispose();

	}

	public void browse() throws Exception {
		try {
			if (conn == null) {
				connect();
			}
			String sql = "select ID, NAME from TEST ";
			Statement prepStmt = conn.createStatement();
			ResultSet rs = prepStmt.executeQuery(sql);
			while (rs.next()) {
				System.out.println("1: " + rs.getInt("ID") + "\t 2: "
						+ rs.getString("NAME"));
			}
		} finally {
			close();
		}
	}

	public void browseTcpServer() throws Exception {
		String driver = "org.h2.Driver";
		String URL_1 = "jdbc:h2:tcp://localhost/~/test";
		String URL = "jdbc:h2:tcp://10.121.37.46:" + Settings.PORT + "/~/test";

		close();

		Class.forName(driver);
		conn = DriverManager.getConnection(URL, "sa", "");
		try {
			String sql = "select ID, NAME from TEST ";
			Statement prepStmt = conn.createStatement();
			ResultSet rs = prepStmt.executeQuery(sql);
			System.out.println("\t---------");
			while (rs.next()) {
				System.out.println("1: " + rs.getInt("ID") + "\t 2: "
						+ rs.getString("NAME"));
			}
			System.out.println("\t---------");
		} finally {
			close();
		}

	}
}
